package com.example.demo.lambda;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @Description:
 * @Author: xiatian
 * @CreateTime: 2021/7/15
 * @Company: kangxu
 */
public class TestLambda {
    List<Employee> filterEmployees = Arrays.asList(
            new Employee("张三", 18, 9999.99),
            new Employee("李四", 38, 666.66),
            new Employee("王五", 26, 5555.55),
            new Employee("王五", 8, 8878.98),
            new Employee("田七", 57, 1234.67)
    );


    @Test
    public void getAge() {
        filterEmployees.stream().filter(x -> x.getAge() > 35).forEach(System.out::println);
    }

    @Test
    public void getName() {
        filterEmployees.stream().map(Employee::getName).forEach(System.out::println);
    }

    List<Integer> integers = Arrays.asList(
            10, 12, 14, 15, 34, 45, 65, 100, 102, 3, 6, 78, 34, 98, 1, 23, 1380
    );

    @Test
    public void forEachLoopMaxInteger() {
        long start = System.currentTimeMillis();
        int max = Integer.MIN_VALUE;
        for (Integer i : integers) {
            max = Integer.max(max, i);
        }
        long end = System.currentTimeMillis();
        System.out.println("foreach循环花费时间：" + (end - start));
    }

    @Test
    public void lambdaIntStreamMaxInteger() {
        long start = System.currentTimeMillis();
        Integer max = IntStream.of(10, 12, 14, 15, 34, 45, 65, 100, 102, 3, 6, 78, 34, 98, 1, 23, 1380).reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
        long end = System.currentTimeMillis();
        System.out.println("intStream循环花费时间：" + (end - start));
    }

    @Test
    public void lambdaParallelMaxInteger() {
        long start = System.currentTimeMillis();
        Integer max = integers.parallelStream().reduce(Integer.MIN_VALUE, (a, b) -> Integer.max(a, b));
        long end = System.currentTimeMillis();
        System.out.println("lambda循环花费时间：" + (end - start));
    }

    @Test
    public void testFilter() {
        Integer[] sixNums = {1, 2, 3, 4, 5, 6};
        Integer[] evens = Stream.of(sixNums).filter(n -> n % 2 == 0).toArray(Integer[]::new);
        String text = "abcdefg";
        System.out.println(Optional.ofNullable(text).map(x -> x.getBytes().length).orElse(-1));
        Double mini = Double.MAX_VALUE;
        double minivaule = Stream.of(-1.5, 1.0, -3.0, 2.0, -2.0, 9.0).reduce(mini, (a, b) -> Double.min(a, b));
        double secondType = Stream.of(-1.5, 1.0, -3.0, 2.0, -2.0, 9.0).reduce(mini, Double::min);
        System.out.println(minivaule);
        System.out.println(minivaule);

    }

}

